const downloads = {}
const apis = {
    quesApi: '/zujuan-api/question/list',
    groupApi: '/zujuan-api/question/batch',
    wordApi: 'https://static.zxxk.com/zujuan/zjms/static/activity/aop.js',
    analyzeApi: '/zujuan-api/question_analyze',
}
chrome.downloads.onChanged.addListener((delta) => {
    if (delta.state && delta.state.current === 'complete' && downloads[delta.id]) {
        sendMessage('downloadComplete', downloads[delta.id])
        delete downloads[delta.id]
    }
})
chrome.downloads.onCreated.addListener((delta) => {
    const type = delta.finalUrl.split(".").pop()
    if ((type.startsWith("docx") || type.startsWith("zip")) && delta.finalUrl.startsWith('')) {
        downloads[delta.id] = delta.finalUrl
    }
})
chrome.webRequest.onCompleted.addListener(requestListener, { urls: ["*://zujuan.xkw.com/*", "*://*.zxxk.com/*"] })
function requestListener (details) {
    const type = filterApi(details.url)
    if (type) {
        sendMessage(type, details.url, details.tabId)
    }
}
function sendMessage (type, data, tabid) {
    if (tabid) {
        chrome.tabs.sendMessage(tabid, { type, data })
    } else {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs && tabs.length) {
                chrome.tabs.sendMessage(tabs[0].id, { type, data })
            }
        })
    }
}

function filterApi (url = '') {
    for (const api in apis) {
        if (apis[api] && url.includes(apis[api])) {
            return api
        }
    }
}

chrome.runtime.onMessage.addListener(handleMessage)

function handleMessage (request, sender, sendResponse) {
    switch (request) {
        case 'restart':
            // 刷新页面
            chrome.tabs.query({ currentWindow: true, title: '*组卷网', url: '*://zujuan.xkw.com/*/*' }, (tabs) => {
                const id = tabs[0].id
                console.log(id)
                setTimeout(() => {
                    chrome.tabs.update(id, { active: true })
                    chrome.tabs.reload(tabs[0].id)
                }, 300)
            })
            break
        default:
            break
    }
}